<?php
/**
 * Zend Image Manipulation Module
 *
 * LICENSE
 *
 * This source file is subject to the new BSD license that is bundled
 * with this package in the file LICENSE.txt.

 * @category   Zimm
 * @package    Zimm
 * @copyright  Copyright (c) 2012 Kristoffer Ingemansson
 * @license    New BSD License
 * @version    $Id: Fit.php 4 2012-04-14 12:59:16Z kristoffer.ingemansson@gmail.com $
 */

class Zimm_Model_DbTable_Instruction_Fit extends Zimm_Model_DbTable_Instruction_Abstract
{
    /**
     * Fith image inside specified dimensions.
     *
     * @param resource $image GD resource
     * @param string $savePath Target save path
     * @param array $params Instruction arguments
     * @return boolean Indicates if image was altered
     */
    protected function _process(&$image, $savePath, $params)
    {
        $targetWidth = isset($params['width']) ? $params['width'] : NULL;
        $targetHeight = isset($params['height']) ? $params['height'] : NULL;
        $targetArea = isset($params['area']) ? $params['area'] : NULL;
        if ($targetWidth || $targetHeight || $targetArea) {
            $toWidth = $fromWidth = imagesx($image);
            $toHeight = $fromHeight = imagesy($image);

            if ($targetWidth && $fromWidth > $targetWidth) {
                $toHeight = (int)($toHeight * $targetWidth / $toWidth);
                $toWidth = $targetWidth;
            }

            if ($targetHeight && $fromHeight > $targetHeight) {
                $toWidth = (int)($toWidth * $targetHeight / $toHeight);
                $toHeight = $targetHeight;
            }

            $toArea = $toWidth * $toHeight;
            if ($targetArea && $toArea > $targetArea) {
                $aspect = $fromWidth / $fromHeight;
                $side = sqrt($targetArea / $aspect);
                $toHeight = (int)$side;
                $toWidth = (int)($side * $aspect);
            }

            if ($toWidth != $fromWidth || $toHeight != $fromHeight) {
                $im_dest = imagecreatetruecolor($toWidth, $toHeight);
                imagecopyresampled($im_dest, $image, 0, 0, 0, 0, $toWidth, $toHeight, $fromWidth, $fromHeight);
                imagedestroy($image);
                $image = $im_dest;
                return true;
            }
        }
        return false;
    }
}